import { ClassifyApi, fetchClassify } from '@/api/premium/category/classify'
import {
  ClassifyItem,
  ClassifyType,
} from '@/api/premium/category/model/classifyModel'
import { useStore } from '@/store'
import { computed, reactive, ref } from 'vue'
import { ClassifyTableState } from '../type'

const generateList = (data: ClassifyItem[], dataList: ClassifyItem[] = []) => {
  for (let i = 0; i < data.length; i++) {
    const node = data[i]
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const { childCateGoryList, ...item } = node
    dataList.push(item)
    if (node.childCateGoryList) {
      generateList(node.childCateGoryList, dataList)
    }
  }
  return dataList
}

const getParentKey = (
  key: string,
  tree: ClassifyItem[]
): string[] | undefined => {
  let parentKey
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i]
    if (node.childCateGoryList) {
      if (node.childCateGoryList.some((item) => item.id === key)) {
        parentKey = node.pids.split(',')
        parentKey.push(node.id)
      } else if (getParentKey(key, node.childCateGoryList)) {
        parentKey = getParentKey(key, node.childCateGoryList)
      }
    }
  }
  return parentKey
}

const useSearchClassify = () => {
  const store = useStore()
  const searchInput = ref()
  const searchValue = ref('')
  const expendKeys = ref<string[]>([])
  const tableStateWrapper = reactive<ClassifyTableState>({
    selectedRowKeys: [],
    tableSize: 'small',
    tableData: [],
    tableColumns: [
      {
        title: '分类名称',
        dataIndex: 'name',
        slots: {
          filterDropdown: 'filterDropdown',
          filterIcon: 'filterIcon',
        },
        customRender: ({ text }) => {
          if (searchValue.value && text.indexOf(searchValue.value) > -1) {
            return (
              <>
                <span>{text.substr(0, text.indexOf(searchValue.value))}</span>
                <span style={{ color: '#f50' }}>{searchValue.value}</span>
                <span>
                  {text.substr(
                    text.indexOf(searchValue.value) + searchValue.value.length
                  )}
                </span>
              </>
            )
          }
          return <span>{text}</span>
        },
        onFilter: () => true,
        onFilterDropdownVisibleChange: (visible) => {
          if (visible) {
            setTimeout(() => {
              searchInput.value.focus()
            }, 0)
          }
        },
      },
      {
        title: 'ID',
        dataIndex: 'id',
      },
      {
        title: '创建人',
        dataIndex: 'addUser',
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
      },
      {
        title: '修改人',
        dataIndex: 'modifyUser',
      },
      {
        title: '修改时间',
        dataIndex: 'updateTime',
      },
      {
        title: '操作',
        dataIndex: 'options',
        width: 50,
        slots: {
          customRender: 'options',
        },
      },
    ],
  })

  const expandedRowKeysChange = (rowKeys: string[]) => {
    expendKeys.value = rowKeys
  }

  const getClassifyList = async () => {
    const { data } = await fetchClassify()
    if (data.childCateGoryList) {
      tableStateWrapper.tableData = data.childCateGoryList.filter(
        (child) => child.type === ClassifyType.IMAGE
      )
    }
  }
  const fetchClassifyLoading = computed(() =>
    store.getters['global/isOpLoading'](ClassifyApi.GET_CLASSIFY_TREE)
  )

  const handleSearch = (selectedKeys: string[], confirm: () => void) => {
    searchValue.value = selectedKeys[0]
    const expanded = generateList(tableStateWrapper.tableData)
      .map((item) => {
        if ((item.name as string).indexOf(selectedKeys[0]) > -1) {
          return getParentKey(item.id, tableStateWrapper.tableData)
        }
        return undefined
      })
      .filter((item) => !!item)
    expanded.forEach((item) => {
      if (item) {
        expendKeys.value.push(...item)
      }
    })
    console.log(expanded, expendKeys.value)
    confirm()
  }

  const handleReset = (clearFilters: () => void) => {
    searchValue.value = ''
    expendKeys.value = []
    clearFilters()
  }

  return {
    tableStateWrapper,
    getClassifyList,
    fetchClassifyLoading,
    handleSearch,
    handleReset,
    searchInput,
    expendKeys,
    expandedRowKeysChange,
  }
}

export default useSearchClassify
